package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.SystemConstants.DEFAULT_PAGE_SIZE;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public Result queryById(Long id) {
        //缓存穿透
        Shop shopRes = queryWithPassThrough(id);
        //互斥锁解决缓存击穿
//        Shop shopRes = null;
//        try {
//            shopRes = queryWithMutex(id);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }

        //逻辑过期解决缓存击穿
//        Shop shopRes = queryWithLogicExpire(id);
//        if (shopRes == null) {
//            return Result.fail("店铺不存在");
//        }
        return Result.ok(shopRes);

    }

    @Override
    public Shop queryWithMutex(Long id) throws InterruptedException {
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;

        //先从redis查缓存，不存在查数据库
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shop = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shop)) {
            Shop shopRes = JSONUtil.toBean(shop, Shop.class);
            return shopRes;
        }
        //空值
        if (shop != null) {
            return null;
        }
        //实现缓存重建
        //获取互斥锁
        boolean flag = tryLock(lockKey);
        if (!flag) {
            //获取失败就休眠并重试
            Thread.sleep(5);
            //重试就采用递归执行即可
            return queryWithMutex(id);
        }
        //获取成功就进行数据库查询并将数据写入redis
        Shop shopRes = getById(id);
        if (shopRes == null) {
            //将空值写入redis
            redisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopRes), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        unlock(lockKey);
        return shopRes;
    }

    @Override
    @Transactional
    public Result update(Shop shop) {
        //先操作数据库后删除缓存
        updateById(shop);
        if (shop.getId() == null) {
            return Result.fail("店铺id为null");
        }
        String key = RedisConstants.CACHE_SHOP_KEY + shop.getId();
        redisTemplate.delete(key);

        return Result.ok();
    }

    /**
     * 基于redis setnx实现锁
     */
    private boolean tryLock(String key) {
        Boolean flag = redisTemplate.opsForValue().setIfAbsent("lock", "1", 10, TimeUnit.SECONDS);
        return flag;
    }

    private void unlock(String key) {
        redisTemplate.delete(key);
    }

    public Shop queryWithPassThrough(Long id) {
        //先从redis查缓存，不存在查数据库
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shop = redisTemplate.opsForValue().get(key);
        if (StrUtil.isNotBlank(shop)) {
            Shop shopRes = JSONUtil.toBean(shop, Shop.class);
            return shopRes;
        }
        //空值
        if (shop != null) {
            return null;
        }
        Shop shopRes = getById(id);
        if (shopRes == null) {
            //将空值写入redis
            redisTemplate.opsForValue().set(key, "", RedisConstants.CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        redisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shopRes), RedisConstants.CACHE_SHOP_TTL, TimeUnit.MINUTES);
        return shopRes;
    }

    //线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTORS = Executors.newFixedThreadPool(10);

    /**
     * 逻辑过期解决缓存击穿
     * @param id
     */
    public Shop queryWithLogicExpire(Long id) {
        //先从redis查缓存，不存在查数据库
        String key = RedisConstants.CACHE_SHOP_KEY + id;
        String shop = redisTemplate.opsForValue().get(key);
        if (StrUtil.isBlank(shop)) {
            return null;
        }
        //命中就进行如下操作
        //反序列化判断是否进行过期
        RedisData redisData = JSONUtil.toBean(shop, RedisData.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        JSONObject data = (JSONObject) redisData.getData();
        Shop shopRes = JSONUtil.toBean(data, Shop.class);
        //数据有效就直接返回
        if (expireTime.isAfter(LocalDateTime.now())) {
            return shopRes;
        }
        //数据无效就开新线程重建缓存
        String lockKey = RedisConstants.LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lockKey);
        if (isLock) {
            //获取成功就开新线程重建缓存
            CACHE_REBUILD_EXECUTORS.submit(
                    () -> {
                        try {
                            //重建缓存
                            this.saveShop2Redis(id, 20L);
                        } catch (Exception e) {
                            throw new RuntimeException(e);
                        }finally {
                            //释放锁
                            unlock(lockKey);
                        }
                    }
            );
        }
        //返回过期的店铺信息
        return shopRes;
    }

    public void saveShop2Redis(Long id, Long seconds) {
        //查询店铺数据
        Shop shop = getById(id);

        //封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(seconds));
        redisData.setData(shop);
        //写入redis
        redisTemplate.opsForValue().set(RedisConstants.CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
        
    }

    @Override
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        //判断是否需要按照坐标进行查询
        if (x==null||y==null){
            // 根据类型分页查询
            Page<Shop> page = query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //按照地理坐标查询
        int from = (current-1)*DEFAULT_PAGE_SIZE;
        int end =current*DEFAULT_PAGE_SIZE;
        String key ="shop:geo:"+typeId;
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = redisTemplate.opsForGeo()
                .search(key, GeoReference.fromCoordinate(x, y), new Distance(5000),
                        RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));

        if (results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> content = results.getContent();
        if (content.size()<=from){
            return Result.ok(Collections.emptyList());
        }
        List<Long> ids = new ArrayList<>(content.size());
        HashMap<String, Distance> map = new HashMap<>(ids.size());
        content.stream().skip(from).forEach(
                r->{
                    String shopId = r.getContent().getName();
                    Distance distance = r.getDistance();
                    ids.add(Long.valueOf(shopId));
                    map.put(shopId,distance);
                }
        );
        //根据id进行批量查询
        String str = StrUtil.join(",",ids);

        List<Shop> shopList = query().in("id", ids).last("order by field (id," + str + ")").list();
        for (Shop shop : shopList) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());

        }
        return Result.ok(shopList);
    }
}
